import React, { useEffect, useState } from 'react'
import './detail.scss'
import axios from '../../axios'

import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-light.css'
import IconFont from '../../components/IconFont/IconFont'
import Button from '../../components/Button/Button'
import WangEditor from '../../components/WangEditor/WangEditor'
import Card from '../../components/Card/Card'
import User from '../../components/User/User'
import { getUser } from '../../utils/storage'

export default function Detail(props) {
  console.log(props)
  const [info, setInfo] = useState({})
  const { id } = props.match.params

  const [content, setContent] = useState('')
  const [list, setList] = useState([])

  const submit = () => {
    if (content === '<p><br></p>') {
      alert('评论不能为空！')
    } else {
      axios.post('/comment', {
        article: info._id,
        user: getUser()._id,
        content
      }).then(res => {
        setList([res.data, ...list])
        setContent('')
      })
    }
  }

  // useEffect(() => {
  //   axios.get('/guestbook', {
  //     pageIndex,
  //     pageSize
  //   }).then(res => {
  //     setList(res.data.records)
  //     setTotal(res.data.total)
  //   })
  // }, [pageIndex, pageSize])

  useEffect(() => {
    console.log('进来了')
    axios.get(`/article/${id}`).then(res => {
      console.log(res)
      setInfo(res.data.article)
      setList(res.data.comments)
    })
  }, [id])

  useEffect(() => {
    if (info._id) {
      // 配置 highlight.js
      hljs.configure({
        // 忽略未经转义的 HTML 字符
        ignoreUnescapedHTML: true
      })
      // 获取到内容中所有的code标签
      const codes = document.querySelectorAll('.article-detail pre code')
      codes.forEach((el) => {
        // 让code进行高亮
        hljs.highlightElement(el)
      })
    }
  }, [info])

  let timer = null
  const like = (id) => {
    if (timer) {
      clearTimeout(timer)
      alert('点赞太频繁，请慢点！')
    }
    timer = setTimeout(() => {
      axios.put('/comment/like', {
        id
      }).then(() => {
        setList(list.map(item => {
          if (item._id === id) {
            return {
              ...item,
              likeNum: item.likeNum + 1
            }
          }
          return item
        }))
      })
    }, 200)
  }
  return (
    <div className='article-detail'>
    <div className='head'>
      <div className='title'>
        <span>{info.title}</span>
      </div>
      <div className='about'>
        <IconFont type='icon-zuozhe' style={{ fontSize: '15px', marginRight: '2px' }}></IconFont>
        <span className='author'>作者：{info.author?.nickname}</span>
        <IconFont type='icon-shijian' style={{ fontSize: '15px', marginRight: '2px' }}></IconFont>
        <span className='time'>发布时间：{info.publishDate}</span>
      </div>
    </div>
    <div className='content'>
      <p dangerouslySetInnerHTML={{ __html: info.content }}></p>
    </div>
    <div className='comment' style={{marginTop: '100px'}}>
      <WangEditor disabled={getUser()._id ? false : true} content={content} getHtml={setContent} />
      <Button onClick={submit} style={{ marginTop: '10px', marginBottom: '30px'}}>发表</Button>
      <div className='list'>
        {
          list?.length ?
            list.map(item => {
              return (
                <Card className='card' key={item._id}>
                  <User style={{ marginBottom: '10px' }} avatar={item.user.avatar} nickname={item.user.nickname}></User>
                  <div className='content' dangerouslySetInnerHTML={{ __html: item.content }}></div>
                  <div className='action-item' style={{cursor: 'pointer'}} onClick={() => like(item._id)}>
                    <IconFont type='icon-dianzan1' style={{fontSize: '18px'}}></IconFont>
                    { item.likeNum > 0 && <span>{item.likeNum}</span> }
                  </div>
                </Card>
              )
            })
            :
            <div style={{ marginTop: '20px' }}>还没有评论！</div>
        }
      </div>
    </div>
  </div>
  )
}
